import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:riki_login/api/base_api.dart';
import 'package:riki_login/pages/staff/staff_register_worker_viewmodel.dart';
import 'package:riki_login/pages/staff/widgets/login_common_widget.dart';
import 'package:riki_login/pages/staff/widgets/login_privacy_widget.dart';
import 'package:riki_login/res/header.dart';
import 'package:riki_login/riki_login.dart';
import 'package:wangyi_yidun_flutter_plugin/wangyi_yidun_flutter_plugin.dart';

///作者：范玉辉
///创建时间：2021/2/8
///说明：注册工人页面

class StaffRegisterWorkerPage extends StatefulWidget {
  @override
  _StaffRegisterWorkerPageState createState() => _StaffRegisterWorkerPageState();
}

class _StaffRegisterWorkerPageState extends BaseScaffoldState<StaffRegisterWorkerPage> {
  late StaffRegisterWorkerViewModel viewModel;
  //焦点
  var eventChannel = const EventChannel("yd_captcha_flutter_event_channel");

  //手机号输入框控制器，此控制器可以监听手机号输入框操作
  TextEditingController _userPhoneController = TextEditingController();
  TextEditingController _userCodeController = TextEditingController();
  //表单状态
  GlobalKey _formKey = GlobalKey();
  bool _isShowClear = false; //是否显示输入框尾部的清除按钮
  bool isAgreement = RikiLogin.instance.isAgreement;
  // 是否按下登录
  bool isTapDown = false;

  // 是否可以登录
  bool isTap = false;

  // 是否按下获取验证码
  bool isTapSendCode = false;

  List<BoxShadow> cardShadow = [
    BoxShadow(
        offset: Offset(0, 6),
        color: RikiLoginColors.cardShadowColor,
        blurRadius: 14.w, //阴影模糊程度
        spreadRadius: -6.w //阴影扩散程度
        ),
  ];

  // 验证手机号
  String? validateUserName(value) {
    // 正则匹配手机号
    RegExp exp = RegExp(r'^(13|14|15|16|17|18|19)\d{9}$');
    if (!exp.hasMatch(value)) {
      return '手机号格式错误!';
    }
    return null;
  }

  @override
  void initState() {
    // 网易滑块回调
    eventChannel.receiveBroadcastStream().listen(_onData, onError: _onError);

    //监听手机号框的输入改变
    _userPhoneController.addListener(() {
      // 监听文本框输入变化，当有内容的时候，显示尾部清除按钮，否则不显示
      if (_userPhoneController.text.length > 0) {
        _isShowClear = true;
      } else {
        _isShowClear = false;
      }
      setState(() {});
    });
    // 验证码输入监听
    _userCodeController.addListener(() {
      if (_userCodeController.text.length > 0) {
        isTap = true;
      } else {
        isTap = false;
      }
      setState(() {});
    });

    super.initState();
  }

  /// 网易验证成功
  void _onData(response) {
    var validate = (response as Map)['validate'];
    if (validate != null && !validate.isEmpty) {
      //发送验证码
      getLoginCode(validate);
    }
  }

  /// 网易验证出现错误
  void _onError(Object error) {
    ToastUtil.showNegativeToast('加载验证码出现错误');
  }

  @override
  bool resizeToAvoidBottomInset() {
    return false;
  }

  isPageObserver() {
    return true;
  }

  @override
  Widget buildBody(BuildContext context) {
    return ProviderWidget<StaffRegisterWorkerViewModel>(
      builder: (context, model, child) {
        return _buildBodyWidget();
      },
      model: StaffRegisterWorkerViewModel(),
      onModelReady: (model) {
        viewModel = model;
        viewModel.initApi(context);
      },
      pageStatusFactory: null,
    );
  }

  @override
  Widget buildAppBar(BuildContext context) {
    return RikiAppBar(
      isBack: true,
      onBackPressed: () => NavigatorUtils.goBack(context),
    );
  }

  Widget _buildBodyWidget() {
    return GestureDetector(
      onTap: () => FocusScope.of(context).requestFocus(FocusNode()),
      child: Container(
        color: RikiLoginColors.app_white,
        margin: EdgeInsets.only(top: 20.w, left: 37.5.w, right: 37.5.w),
        child: Form(
          key: _formKey,
          child: Column(
            children: [
              buildRowText('注册施工工人'),
              Container(
                padding: EdgeInsets.only(top: 37.w),
                child: TextFormField(
                  controller: _userPhoneController,
                  autofocus: true,
                  //光标颜色
                  cursorColor: RikiLoginColors.app_main,
                  cursorWidth: 2,
                  style: TextStyle(color: RikiLoginColors.text_333333, fontSize: 18.sp),
                  keyboardType: TextInputType.number,
                  //设置键盘类型,
                  decoration: InputDecoration(
                    border: InputBorder.none,
                    hintText: "请输入手机号",
                    hintStyle: TextStyle(
                      color: RikiLoginColors.text_999999,
                    ),
                    focusedBorder: UnderlineInputBorder(
                      borderSide: BorderSide(
                        color: RikiLoginColors.app_transparent, //输入框底边线
                      ),
                    ),
                    //尾部添加清除按钮
                    suffixIcon: (_isShowClear)
                        ? GestureDetector(
                            onTap: () {
                              // 清空输入框内容
                              _userPhoneController.clear();
                              viewModel.userPhone = '';
                            },
                            child: Container(
                              padding: EdgeInsets.only(left: 20.w),
                              child: ImageUtil.loadAssetImage(R.libAssetsIcLoginInputClear, width: 24.w, height: 24.w,package: RikiLogin.PACKAGE),
                            ),
                          )
                        : Empty.ui,
                  ),
                  inputFormatters: <TextInputFormatter>[
                    FilteringTextInputFormatter.digitsOnly, //只输入数字
                    LengthLimitingTextInputFormatter(11) //限制长度
                  ],
                  //验证手机号
                  validator: validateUserName,
                  //保存数据
                  onChanged: (String value) {
                    viewModel.userPhone = value;
                  },
                ),
              ),
              Container(
                color: Color.fromRGBO(153, 153, 153, 0.3),
                height: 1,
              ),
              Row(
                children: [
                  Expanded(
                    child: Container(
                      margin: EdgeInsets.only(top: 30.w),
                      child: TextFormField(
                        controller: _userCodeController,
                        autofocus: true,
                        //光标颜色
                        cursorColor: RikiLoginColors.app_main,
                        cursorWidth: 2,
                        style: TextStyle(color: RikiLoginColors.text_333333, fontSize: 18.sp),
                        keyboardType: TextInputType.number,
                        //设置键盘类型
                        decoration: InputDecoration(
                          hintText: "请输入验证码",
                          hintStyle: TextStyle(
                            color: RikiLoginColors.text_999999,
                          ),
                          border: InputBorder.none,
                          focusedBorder: UnderlineInputBorder(
                            borderSide: BorderSide(
                              color: RikiLoginColors.app_white, //输入框底边线
                            ),
                          ),
                        ),

                        inputFormatters: <TextInputFormatter>[
                          WhitelistingTextInputFormatter.digitsOnly, //只输入数字
                          LengthLimitingTextInputFormatter(6) //限制长度
                        ],
                        //保存数据
                        onChanged: (String value) {
                          viewModel.userCode = value;
                        },
                      ),
                    ),
                  ),
                  Container(
                    margin: EdgeInsets.only(top: 30.w),
                    child: Selector(builder: (BuildContext context, int data, Widget? child) {
                      return viewModel.sendCode == '获取验证码'
                          ? GradientBgButton(
                              onTap: () {
                                showCaptcha();
                              },
                              enabled: _userPhoneController.text.length == 11,
                              width: 75.w,
                              height: 25.w,
                              title: viewModel.sendCode,
                              fontSize: 11.sp,
                            )
                          : GestureDetector(
                              onTap: () {
                                if (viewModel.sendCode == '重发') {
                                  showCaptcha();
                                }
                              },
                              child: Container(
                                alignment: Alignment.centerRight,
                                width: 75.w,
                                height: 25.w,
                                child: Selector(builder: (BuildContext context, int data, Widget? child) {
                                  return Text(
                                    viewModel.sendCode,
                                    style: viewModel.sendCode == '重发' ? _textMediumStyle : _textRegularStyle,
                                  );
                                }, selector: (BuildContext context, StaffRegisterWorkerViewModel counterProvider) {
                                  return counterProvider.countdownTime;
                                }),
                              ),
                            );
                    }, selector: (BuildContext context, StaffRegisterWorkerViewModel counterProvider) {
                      return counterProvider.countdownTime;
                    }),
                  ),
                ],
              ),
              Container(
                color: Color.fromRGBO(153, 153, 153, 0.3),
                height: 1,
              ),
              45.vGap,
              Container(
                decoration: BoxDecoration(
                  boxShadow: (viewModel.userPhone.length == 11 && viewModel.userCode.length > 0) ? cardShadow : null,
                ),
                child: GradientBgButton(
                  onTap: () {
                    registerWorker();
                  },
                  enabled: (viewModel.userPhone.length == 11 && viewModel.userCode.length > 0),
                  width: 300.w,
                  height: 44.w,
                  title: "注册",
                  fontSize: 16.sp,
                ),
              ),
              LoginPrivacyWidget(this.isAgreement, (isAgreement) {
                if (mounted)
                  setState(() {
                    this.isAgreement = isAgreement;
                  });
              }),
            ],
          ),
        ),
      ),
    );
  }

  /// 注册
  void registerWorker() async {
    // 关闭键盘
    FocusScope.of(context).requestFocus(FocusNode());
    if (!this.isAgreement) {
      ToastUtil.show("请勾选服务协议!");
      return;
    }
    showLoading(afterDismiss: () {
      RikiLogin.instance.onLoginSuccessCallback(context);
    });
    viewModel.registerWorker().whenComplete(() => hideLoading());
  }

  /// 发送验证码
  Future<void> showCaptcha() async {
    if (viewModel.userPhone.length == 0) {
      print(viewModel.userPhone);
      ToastUtil.show('请输入手机号');
      return;
    }
    // 手机号是否填写
    if (viewModel.userPhone.length < 11 && viewModel.userPhone.length > 0) {
      print(viewModel.userPhone);
      ToastUtil.show('手机号错误，请重新输入');
      return;
    }
    if (viewModel.sendCode != '获取验证码' && viewModel.sendCode != '重发') {
      return;
    }
    //协议是否开着
    if (!this.isAgreement) {
      ToastUtil.show("请勾选服务协议!");
      return;
    }
    // 关闭键盘
    FocusScope.of(context).requestFocus(FocusNode());
    WangyiYidunFlutterPlugin.setup(appKey: RikiLogin.instance.netEasyAppKey);
  }

  // 获取验证码
  void getLoginCode(String neCaptchaValidate) async {
    showLoading();
    viewModel.sendSmsCodeFun(neCaptchaValidate).whenComplete(() => hideLoading());
  }

  // 验证手机号
  bool validateUserPhone(value) {
    // 正则匹配手机号
    RegExp exp = RegExp(r'^(13|14|15|16|17|18|19)\d{9}$');
    if (!exp.hasMatch(value)) {
      return false;
    }
    return true;
  }

  TextStyle _textMediumStyle = TextStyle(color: RikiLoginColors.app_main, fontSize: 11.sp, fontWeight: FontWeightExt.medium);
  TextStyle _textRegularStyle = TextStyle(color: RikiLoginColors.text_333333, fontSize: 11.sp);
}
